import { util } from '@kit.ArkTS';

/**
 * 字节操作工具类
 */
export class ByteUtils {
  /**
   * 字符串转字节数组
   * @param str
   * @returns
   */
  static stringToUtf8Bytes(str) {
    const textEncoder = new util.TextEncoder("utf-8")
    return textEncoder.encodeInto(str)
  }

  /**
   * 字节数组转字符串
   * @param array
   * @returns
   */
  static utf8BytesToString(array) {
    const textDecoder = util.TextDecoder.create("utf-8")
    return textDecoder.decodeWithStream(array, { stream: false })
  }

  /**
   * 字节数组转16进制字符串
   * @param uint8Array
   * @returns
   */
  static bytesToHexStr(uint8Array) {
    return Array.prototype.map
      .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
      .join('');
  }

  /**
   *  16进制字符串转字节数组
   * @param hexString
   * @returns
   */
  static hexStrToBytes(hexString) {
    var byteArray = [];
    for (var i = 0; i < hexString.length - 1; i += 2) {
      var hexValue = parseInt(hexString.substr(i, 2), 16);
      if (!isNaN(hexValue)) {
        byteArray.push(hexValue);
      } else {
        throw new Error("Invalid input");
      }
    }
    return new Uint8Array(byteArray);
  }
}